package com.ourmovieguy;

import javax.jdo.JDOHelper;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

public final class PM {
    private static final PersistenceManagerFactory pmfInstance =
        JDOHelper.getPersistenceManagerFactory("transactions-optional");

    private PM() {}

    public static PersistenceManagerFactory get() {
        return pmfInstance;
    }
    
    public static <T> T getObjectById(Class<T> cl, Object id)
    {
    	PersistenceManager pm = PM.get().getPersistenceManager();
    	
    	T ret;
    	try {
    		ret = pm.getObjectById(cl, id);
    	} catch (JDOObjectNotFoundException e1) {
    		ret = null;
    	} catch (Exception e2) {
    		e2.printStackTrace();
    		ret = null;
    	} finally {
    		pm.close();
    	}

    	return ret;
    }

	public static <T> Query newQuery(Class<T> cl) {
    	PersistenceManager pm = PM.get().getPersistenceManager();
    	Query ret = null;
    	try {
    	 ret = pm.newQuery(cl);
    	} catch (Exception ex) {
    		ex.printStackTrace();
    	} finally {
    		pm.close();
    	}
    	
    	return ret;
	}

	public static <T> void makePersistent(T obj) {
		PersistenceManager pm = PM.get().getPersistenceManager();
		try {
			pm.makePersistent(obj);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			pm.close();
		}
	}
}